using AutoMapper;
using MediatR;
using S.M.SmartMedical.API.Write.Application.Command;
using S.M.SmartMedical.Domain.DTOs;
using S.M.SmartMedical.Domain.Entities;
using S.M.SmartMedical.Domain.Enums;
using S.M.SmartMedical.ErrorCode;
using S.M.SmartMedical.Infrastructure;
using S.M.SmartMedical.Infrastructure.BaseRepository;

namespace S.M.SmartMedical.API.Write.Application.Handler
{
    /// <summary>
    /// 更新轮播图命令处理器
    /// </summary>
    public class UpdateCarouselHandler : IRequestHandler<UpdateCarouselCommand, APIResult<CarouselDto>>
    {
        private readonly IRepository<Carousel> _carouselRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<UpdateCarouselHandler> _logger;
        private readonly MyDbContext _context;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="carouselRepository">轮播图仓储</param>
        /// <param name="mapper">对象映射器</param>
        /// <param name="logger">日志记录器</param>
        /// <param name="context">数据库上下文</param>
        public UpdateCarouselHandler(
            IRepository<Carousel> carouselRepository,
            IMapper mapper,
            ILogger<UpdateCarouselHandler> logger,
            MyDbContext context)
        {
            _carouselRepository = carouselRepository;
            _mapper = mapper;
            _logger = logger;
            _context = context;
        }

        /// <summary>
        /// 处理更新轮播图命令
        /// </summary>
        /// <param name="request">更新轮播图命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>更新结果</returns>
        public async Task<APIResult<CarouselDto>> Handle(UpdateCarouselCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始处理更新轮播图，ID：{Id}", request.Carousel.Id);

                // 检查轮播图是否存在
                var existingCarousel = await _carouselRepository.GetByIdAsync(request.Carousel.Id);
                if (existingCarousel == null || existingCarousel.IsDeleted)
                {
                    _logger.LogWarning("轮播图不存在或已删除，ID：{Id}", request.Carousel.Id);
                    return new APIResult<CarouselDto>
                    {
                        Code = APIEnum.Fail,
                        Message = "轮播图不存在或已删除",
                        Data = null!
                    };
                }

                // 更新轮播图信息
                existingCarousel.Title = request.Carousel.Title;
                existingCarousel.ImageUrl = request.Carousel.ImageUrl;
                existingCarousel.LinkUrl = request.Carousel.LinkUrl;
                existingCarousel.Status = request.Carousel.Status;
                existingCarousel.SortOrder = request.Carousel.Sort;
                existingCarousel.UpdateTime = DateTime.Now;
                existingCarousel.UpdateUserName = "admin"; // 实际应用中应该从登录用户获取

                // 更新到仓储
                var result = await _carouselRepository.UpdateAsync(existingCarousel);

                // 保存到数据库
                var saveResult = await _context.SaveChangesAsync(cancellationToken);

                if (saveResult > 0)
                {
                    _logger.LogInformation("轮播图更新成功，ID：{Id}", existingCarousel.Id);

                    // 映射返回数据
                    var carouselDto = _mapper.Map<CarouselDto>(existingCarousel);
                    return new APIResult<CarouselDto>
                    {
                        Code = APIEnum.OK,
                        Message = "轮播图更新成功",
                        Data = carouselDto
                    };
                }
                else
                {
                    _logger.LogError("轮播图更新失败，数据库保存失败，ID：{Id}", request.Carousel.Id);
                    return new APIResult<CarouselDto>
                    {
                        Code = APIEnum.Fail,
                        Message = "轮播图更新失败，请稍后重试",
                        Data = null!
                    };
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新轮播图过程中发生异常，ID：{Id}", request.Carousel.Id);
                return new APIResult<CarouselDto>
                {
                    Code = APIEnum.Fail,
                    Message = "更新轮播图失败，系统异常",
                    Data = null!
                };
            }
        }
    }
}